package cn.wolfcode.shop.resolver;

import cn.wolfcode.shop.domain.User;
import cn.wolfcode.shop.redis.MemberServerKeyPrefix;
import cn.wolfcode.shop.redis.RedisTemplate;
import cn.wolfcode.shop.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver{

    @Autowired
    private RedisTemplate redisTemplate;

    // 当springMVC遍历参数解析器的时候，第一个返回true的参数解析器去处理对应的参数
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType() == User.class;
    }

    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String token = CookieUtil.getCookie(request, CookieUtil.TOKEN_NAME);
        if (StringUtils.isEmpty(token)){
            return null;
        }
        User user = redisTemplate.get(MemberServerKeyPrefix.USER_TOKEN, token, User.class);
        return user;
    }
}
